﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using GameSchool.Models.Interfaces;
using GameSchool.Models;
using GameSchool.Models.Repositories;
using GameSchool.Models.ViewModels;

namespace GameSchool.Controllers
{
    public class HomeController : Controller
    {

        //Displays the home page - pretty much just the newest newsItems in all courses.
        public ActionResult Index()
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("Account", "LogOn");


            NewsRepository rep  = new NewsRepository();

            var repList = rep.GetNews().Take(10) ;

            List<NewsItemViewModel> modelList = new List<NewsItemViewModel>();
  

            foreach (var n in repList)
            {
                NewsItemViewModel model = new NewsItemViewModel();
                model.date = n.DatePub;
                model.parseCourseID(n.CourseID);
                model.parseAuthorID(n.Author);
                model.ID = n.ID;
                model.Title = n.Title;
                model.Body = n.Content;
                modelList.Add(model);
            }


            return View(modelList);

        }
     
     //Returns the users total points & achivements and returns them to the homepage.
    [HttpGet]
        public JsonResult GetPoints()
        {
            var rep = new PointsRepository();
            //Retrives the guID for the currently logged in user.
            var userID = (Guid)Membership.GetUser().ProviderUserKey;
  
            var pointsList = rep.GetTotalPoints();
            var userPoints = (from p in pointsList
                              where p.UserID == userID
                              select p.Points).Sum();

            return Json(userPoints, JsonRequestBehavior.AllowGet);

        }
        //Returns the courses that the user is in - or all courses if user is Admin.
         public JsonResult GetCourses()
        {
            var rep = new CourseRepository();
             //Admin gets all courses.
            if (User.IsInRole("admin"))
            {
                var courseList = rep.GetCourses();
                return Json(courseList, JsonRequestBehavior.AllowGet);
            }
            else
            {
                //If not admin we just get the courses for this user.
                var courseList = rep.GetCoursesByUserID((Guid)Membership.GetUser().ProviderUserKey);
                return Json(courseList, JsonRequestBehavior.AllowGet);
            }
        }

        //Returns a model containing user points within a specific course.
         public JsonResult GetCoursePoints(int? ID)
         {
             
             //Hook up to the DB and get the users ID.
             GameSchoolDBDataContext db = new GameSchoolDBDataContext();
             var userID = (Guid)Membership.GetUser().ProviderUserKey;
             
             //This is a model we'll be using to collect the information into.
             var CoursePointsModel = new CoursePointsModel();

             //Get a list of users, and the sum of their points for this course.. We also order the list by points.
             var userPointsList = from p in db.AssignmentScores
                                  group p by p.UserID into g
                                  orderby g.Sum(p => p.Points) ascending
                                 select new KeyValuePair<Guid?, int?>(g.Key, g.Sum(p => p.Points));

             //Find out where in the list the current user is. So pretty ..
             PointsRepository prep = new PointsRepository();
             PointsViewModel pview = new PointsViewModel();

             Guid guid = new Guid();
             //Geting the clients UserID from the login
             guid = (Guid)Membership.GetUser().ProviderUserKey;
             var pointsForLevel = prep.GetTotalPointsForCourse(ID);
             var pointsAndPosition = prep.GetHighScoresAndPositionFromCourse(guid, pointsForLevel);
             int? CurrentPosition;
             foreach (var p in pointsAndPosition)
             {
                 if (p.userID == guid)
                 {
                     pview = p;
                 }

             }
             int i = 1;
             CurrentPosition = pview.position;
             foreach (var p in pointsAndPosition)
             {
                 if (i == CurrentPosition - 1)
                 {
                     CoursePointsModel.abovePoints = p.myPoints;
                 }
                 if (i == CurrentPosition + 1)
                 {
                     CoursePointsModel.belowPoints = p.myPoints;
                 }
                 i++;

             }
             CoursePointsModel.totalPoints = pview.myPoints;

             int currentPosition = Convert.ToInt32(CurrentPosition);

             //Now we just need the information for the current level. Since the function doesn't know what level we're currently on we have to plock that out first..
             var pRep = new PointsRepository();

             var currentLevel = (from l in db.Levels
                                          from u in db.IsInCourses
                                          where u.CourseID == ID && u.UserID == userID
                                          where l.CourseID == ID
                                          orderby l.LevelNr descending
                                          select l.LevelNr).FirstOrDefault();

             CoursePointsModel.currentPosition = currentPosition;
             CoursePointsModel.levelMaxPoints = pRep.GetMaxLevelPoints(currentLevel, userID);
             CoursePointsModel.levelPoints = pRep.GetLevelPoints(currentLevel, userID);

                                        

             return Json(CoursePointsModel, JsonRequestBehavior.AllowGet);
         }

        //Returns a model containing points information for the users home page.
         public JsonResult GetMainPoints()
         {

             var userID = (Guid)Membership.GetUser().ProviderUserKey;
             var db = new GameSchoolDBDataContext();

             //First we find out in what courses the user is a student in.
             var courseList =   from c in db.IsInCourses
                                       where c.UserID == userID && c.IsTeacher == false
                                       select c.CourseID;

             var pointsRep = new PointsRepository();
             var coursePoints = new List<MainPointsModel>();
             var levelRep = new LevelRepository();
             foreach (int c in courseList)
             {
                 var pointsModel = new MainPointsModel();

                 pointsModel.maxPoints = 0;

                 var levelList = levelRep.GetLevelsByCourseID(c);
                 foreach (var l in levelList)
                 {
                     pointsModel.maxPoints = pointsRep.GetMaxLevelPoints(l.ID, userID) + pointsModel.maxPoints;
                 }

                 pointsModel.userPoints = pointsRep.GetCoursePoints(c, userID);
                 pointsModel.courseName = (from course in db.Courses
                                              where course.ID == c
                                              select course.Name).SingleOrDefault();
                 pointsModel.courseID = c;

                 coursePoints.Add(pointsModel);
    
             }

             return Json (coursePoints, JsonRequestBehavior.AllowGet);
         }
    }

}
